import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/constans/dict_data_info.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/get_dict_all_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/common/risk_tree_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/double_control/get_base_control_measure_by_id_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/double_prevention_page/risk_control_page/risk_security_identification_page/risk_security_identification_controller.dart';
import 'package:get/get.dart';

class RiskOnClickAddStepPageController extends GetxController {
  ///管控措施描述
  String descriptionControlMeasures = '';

  ///管控手段
  String controllerMeasures = '';
  String controllerMeasuresName = '';

  ///管控措施层级
  String hierarchControlMeasures = '';
  String hierarchControlMeasuresName = '';

  ///隐患排查条目
  String hiddenDangerInvestigationItems = '';

  ///管控措施分类1
  String classificationControlMeasures1 = '';
  String classificationControlMeasures1Name = '';

  ///管控措施分类2
  String classificationControlMeasures2 = '';
  String classificationControlMeasures2Name = '';

  ///管控措施分类3
  String classificationControlMeasures3 = '';

  ///后果降低值
  String consequenceReductionValue = '';

  ///可能性降低值
  String likelihoodReductionValue = '';

  ///默认新增
  bool addAndUpdate = true;

  /// 选中的 隐患排查任务管理_管控方式
  GetDictAllEntity? dictEntity;

  ///层级2子集
  List<GetDictAllEntity>? dictionaryDetails = [];

  /// 选中的节点
  RiskTreeEntity selectedEntity = RiskTreeEntity();
  bool isShow = false;
  List<GetDictAllEntity> riskControlClassificationOfControlMeasures1FirstType = [];

  @override
  void onInit() {
    super.onInit();
    initRiskControlClassificationOfControlMeasures1FirstType();
    selectedEntity = Get.arguments['riskStepId'] as RiskTreeEntity;
    if (Get.arguments['editId'] != null) {
      addAndUpdate = false;
      isShow = true;
      getRiskStepById();
    }
  }

  /// 请求参数
  Map<String, dynamic> queryParameters = {};

  ///获取相应数据
  GetBaseControlMeasureByIdEntity? data = GetBaseControlMeasureByIdEntity();

  getRiskStepById() async {
    queryParameters['id'] = Get.arguments['editId'];
    final res = await HttpUtil()
        .generateGetRequest<GetBaseControlMeasureByIdEntity>(
          Interface.getBaseControlMeasureById,
          queryParameters: queryParameters,
        )
        .execute();
    res.onSuccess((result) {
      if (result.data != null) {
        data = result.data!;
      }
    });
    descriptionControlMeasures = data?.riskMeasureDesc ?? '';
    controllerMeasures = data?.dataSrc ?? '';
    controllerMeasuresName = data?.dataSrcLabel ?? '';
    hierarchControlMeasures = data?.riskMeasureLevel ?? '';
    hierarchControlMeasuresName = data?.riskMeasureLevelLabel ?? '';
    hiddenDangerInvestigationItems = data?.troubleshootContent ?? '';
    classificationControlMeasures1 = data?.classify1 ?? '';
    classificationControlMeasures1Name = data?.classify1Label ?? '';
    classificationControlMeasures2 = data?.classify2 ?? '';
    classificationControlMeasures2Name = data?.classify2Label ?? '';
    classificationControlMeasures3 = data?.classify3 ?? '';
    consequenceReductionValue = '${data?.consequenceReduction}';
    likelihoodReductionValue = '${data?.probabilityReduction}';

    ///通过层级1获取层级2赋值
    for (GetDictAllEntity value in riskControlClassificationOfControlMeasures1FirstType) {
      if (value.dictionaryLabel == data?.classify1Label) {
        dictionaryDetails = value.dictionaryDetails;
      }
    }
    update();
  }

  /// 管控措施层级
  void selectMeasureLevelType() async{
    final List<GetDictAllEntity> dictList = await DictDataInfo.getDictionaryDataByTree(dictionaryType: 'measure_level');
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '管控措施层级',
      dataList: dictList,
      checkedList: [dictEntity ?? GetDictAllEntity()],
      isMultiple: false,
      onCallBack: (value) {
        dictEntity = value[0];
        hierarchControlMeasures = value[0].getId();
        hierarchControlMeasuresName = value[0].getShowName();
        update();
      },
    );
  }

  /// 管控手段
  void selectHiddenDangerInvestigationTaskControlMeasuresType() async {
    final List<GetDictAllEntity> dictList = await DictDataInfo.getDictionaryDataByTree(dictionaryType: 'hidden_danger_investigation_task_control_measures');
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '管控手段',
      dataList: dictList,
      checkedList: [dictEntity ?? GetDictAllEntity()],
      isMultiple: false,
      onCallBack: (value) {
        dictEntity = value[0];
        controllerMeasures = value[0].getId();
        controllerMeasuresName = value[0].getShowName();
        update();
      },
    );
  }

  /// 风险管控_管控措施分类1 层级1
  void selectRiskControlClassificationOfControlMeasures1FirstType() {
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '管控措施分类1',
      dataList: riskControlClassificationOfControlMeasures1FirstType,
      checkedList: [dictEntity ?? GetDictAllEntity()],
      isMultiple: false,
      onCallBack: (value) {
        dictionaryDetails = value[0].dictionaryDetails!;
        classificationControlMeasures1 = value[0].getId();
        classificationControlMeasures1Name = value[0].getShowName();
        isShow = true;
        update();
      },
    );
  }

  /// 风险管控_管控措施分类2  层级2
  void selectRiskControlClassificationOfControlMeasures1First2Type() {
    CustomSelectFunction.selectMultipleBottomSheet<GetDictAllEntity>(
      title: '管控措施分类2',
      dataList: dictionaryDetails!,
      checkedList: [dictEntity ?? GetDictAllEntity()],
      isMultiple: false,
      onCallBack: (value) {
        dictEntity = value[0];
        classificationControlMeasures2 = value[0].getId();
        classificationControlMeasures2Name = value[0].getShowName();
        update();
      },
    );
  }

  ///新增或更新风险分析措施
  void addRiskStep() async {
    if (descriptionControlMeasures.isEmpty) {
      AppToast.showWarning('请输入管控措施描述');
      return;
    }
    if (controllerMeasures.isEmpty) {
      AppToast.showWarning('请选择管控手段');
      return;
    }
    if (hierarchControlMeasures.isEmpty) {
      AppToast.showWarning('请选择管控措施层级');
      return;
    }
    if (hiddenDangerInvestigationItems.isEmpty) {
      AppToast.showWarning('请选择隐患排查条目');
      return;
    }
    if (classificationControlMeasures1.isEmpty) {
      AppToast.showWarning('请选择管控措施分类1');
      return;
    }
    if (classificationControlMeasures2.isEmpty) {
      AppToast.showWarning('请选择管控措施分类2');
      return;
    }
    if (consequenceReductionValue.isEmpty) {
      AppToast.showWarning('请输入后果降低值');
      return;
    }
    if (likelihoodReductionValue.isEmpty) {
      AppToast.showWarning('请输入可能性降低值');
      return;
    }
    // 获取部门单位接口
    final res = await HttpUtil().generatePostRequest(addAndUpdate ? Interface.insertBaseControlMeasure : Interface.updateBaseControlMeasure, data: {
      'classify1': classificationControlMeasures1, //管控措施分类1：（工程技术：1；维护保养：2；操作行为：3；应急措施：4）
      'classify2': classificationControlMeasures2, //管控措施分类2: 工艺控制:1-1；关键设备/部件：1-2；安全附件：1-3；安全仪表：1-4；其它：1-5；动设备：2-1；静设备：2-2；其它：2-3；人员资质：3-1；操作记录：3-2；
      'classify3': classificationControlMeasures3, //管控措施分类3: 由企业自行定义。
      'consequenceReduction': consequenceReductionValue, //	后果降低值
      'dataSrc': controllerMeasures, //管控手段
      'id': addAndUpdate ? null : Get.arguments['editId'], //	自增id，如果是新增则该参数不需要
      'probabilityReduction': likelihoodReductionValue, //可能性降低值
      'riskEventId': selectedEntity.id, //风险分析事件uuid
      'riskMeasureDesc': descriptionControlMeasures, //管控措施描述
      'riskMeasureLevel': hierarchControlMeasures, //管控措施层级（数据字典）
      'troubleshootContent': hiddenDangerInvestigationItems, //隐患排查内容
    }).execute(isShowLoading: true);
    res.onSuccess((result) {
      Get.back();
      // 刷新列表
      final RiskSecurityIdentificationController riskController = Get.find();
      riskController.globalKey.currentState?.onRefresh();
    });
    res.onError((result) {
      AppToast.showError('新增失败~');
    });
  }

  ///选择
  void showFireWay() {}

  void isBool() {
    update();
  }

  void initRiskControlClassificationOfControlMeasures1FirstType() async {
    riskControlClassificationOfControlMeasures1FirstType =
        await DictDataInfo.getDictionaryDataByTree(dictionaryType: 'risk_control_classification_of_control_measures1_first');
  }
}
